package com.thread.queue;

import java.sql.Time;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class DelayQueueTest {

    public static void main(String[] args) {
        BlockingQueue<DelayItem> delayQueue = new DelayQueue<>();
        delayQueue.add(new DelayItem(5, 1000));
        delayQueue.add(new DelayItem(6, 2000));
        delayQueue.add(new DelayItem(3, 3000));
        delayQueue.add(new DelayItem(2, 4000));
        delayQueue.add(new DelayItem(7, 5000));
        delayQueue.add(new DelayItem(8, 3000));
        delayQueue.add(new DelayItem(10, 4000));
        System.out.println("poll()：" + delayQueue.poll());
        System.out.println("peek()：" + delayQueue.peek().getValue());
        try {
            for(;;){
                System.out.println("take()：" + delayQueue.take().getValue());
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    static class DelayItem implements Delayed{

        private long expireTime;
        private int value;

        public DelayItem(int value, long expireTime) {
            this.value = value;
            this.expireTime = System.currentTimeMillis() + expireTime;
        }

        @Override
        public long getDelay(TimeUnit unit) {
            return unit.convert(expireTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
        }

        @Override
        public int compareTo(Delayed o) {
            DelayItem delayItem = (DelayItem) o;
            if(delayItem.getValue() % 2 == 0){
                return 1;
            }else if(delayItem.getValue() < 0){
                return -1;
            }
            return 0;
        }

        public int getValue() {
            return value;
        }
    }
}

